package com.hunanUniversity.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class DB {
   Connection ct=null;
   PreparedStatement ps=null;
   ResultSet rs=null;
   
   public DB(){
	   try{
		   Class.forName("com.mysql.jdbc.Driver");
		   ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename=mysql","root","123456");
	   }catch(Exception ex){
		   ex.printStackTrace();
	   }
   }
   
   public UserBean checkUser(String username,String password){
	   try{
		 ps=ct.prepareStatement("select * from userTable where username=? and password=?");
		 ps.setString(1, username);
		 ps.setString(2, password);
	     rs=ps.executeQuery();
		 UserBean ub=new UserBean();
		 while(rs.next()){
			 ub.setId(rs.getInt(1));
			 ub.setUsername(rs.getString(2));
			 ub.setPassword(rs.getString(3));
			 return ub;
		 }
		 return null;
	   }catch(Exception ex){
		   ex.printStackTrace();
		   return null;
	   }
	 
   }
   
  public ArrayList findLyInfo(){
	  try{
		  ArrayList al=new ArrayList();
		  ps=ct.prepareStatement("select*from messageTable");
		  ResultSet rs=ps.executeQuery();
		  while(rs.next()){
			  MessageBean ly=new MessageBean();
			  ly.setId(rs.getInt(1));
			  ly.setUserid(rs.getInt(2));
			  ly.setDate(rs.getDate(3));
			  ly.setTitle(rs.getString(4));
			  ly.setContent(rs.getString(5));
			  al.add(ly);
		  }
		  return al;
	  }catch(Exception e){
		  e.printStackTrace();
		  return null;
	  }
  } 
   
  public boolean insertUser(String username,String pwd){
	  try{
		  ps=ct.prepareStatement("insert into userTable values(?,?)");
		  ps.setString(1,username);
		  ps.setString(2,pwd);
		  ps.executeUpdate();
		  return true;
	  }catch(Exception e){
		  e.printStackTrace();
		  return false;
	  }
  }
  
  public String getUserName(int userid){
	  String username=null;
	  try {
		ps=ct.prepareStatement("select username from userTable where id=?");
		ps.setInt(1, userid);
		rs=ps.executeQuery();
		while(rs.next()){
			username=rs.getString(1);
		}
		return username;
		
		
	} catch (Exception e) {
		e.printStackTrace();
		return null;
		// TODO: handle exception
	}
	  
  }
  
  public boolean addInfo(MessageBean mb){
	  try{
		  ps=ct.prepareStatement("insert into messgeTable values(?,?,?,?)");
		  ps.setInt(1, mb.getId());
		  ps.setDate(2, mb.getDate());
		  ps.setString(3, mb.getTitle());
		  ps.setString(4, mb.getContent());
		  ps.executeUpdate();
		  return true;
	  }catch(Exception e){
		  e.printStackTrace();
		  return false;
	  }
  }
}
